'''

Case Type： 数据库系统
Case Name： 数据库正常运行时,终止主进程，进程终止前已提交数据不丢失。
Create At:  2020/06/23
@zou_jialiang0505328126
Descption:  1.	持续执行事务2.	在事务执行过程中终止主进程3.	重启数据库查询数据

history：
created： 2020/06/23  created by @wan005
'''
import os
import unittest
from yat.test import Node
import time
import _thread
import queue
from yat.test import macro
# import PgSql

import sys

sys.path.append(sys.path[0] + "/../")
from testcase.utils.PgSql import PgSql
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *
from testcase.utils.Common import Common


class KillDbPID(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case114.py start------------')
        self.rootNode = Node()
        self.dbUserNode = Node(node='dbuser')
        self.PG_LOG_PATH = macro.PG_LOG_PATH
        self.TPCC_PATH = macro.TPCC_PATH
        self.TPCC_RES = queue.Queue()
        self.com = Common()
        self.t_name = 'test_table'

    def test_killdbpid(self):
        # 建表
        msg = self.com.createLargeNumTable(self.dbUserNode, self.t_name, 1, 10)
        self.log.info(msg)
        # 插数据
        sql = f"insert into {self.t_name} values (1,'aaa');"
        _thread.start_new_thread(self.sh.cycle_exec_sql, (sql, 100000))

        time.sleep(1)

        self.log.info('kill opengauss PID')
        # get_pid_cmd = 'lsof -i:{port} | grep gaussdb'.replace('{port}', self.rootNode.db_port)
        # 最新版本数据库进程command变更成了GaussMast，因而取消对gaussdb的匹配
        msg = self.com.kill_pid(self.rootNode, 9)
        self.log.info(msg)
        self.assertEqual(msg, '')

        self.log.info('restart opengauss')
        is_started = self.sh.startDbCluster()

        self.assertTrue(is_started)
        time.sleep(20)

        select_tbl_sql = f'select count(*) from {self.t_name};'
        self.log.info(select_tbl_sql)
        result = self.sh.executDbSql(select_tbl_sql)
        self.log.info(result)
        if result.split()[2].strip() is not None:
            self.assertTrue(int(result.split()[2].strip()) > 0)

    def tearDown(self):
        # 清理环境，删除表
        msg = self.com.createLargeNumTable(self.dbUserNode, self.t_name, del_sign=True)
        self.log.info(msg)

        self.log.info('this is tearDown')
        # recover pg_log permission
